
package com.wulian.user.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.wulian.user.mapper.SysRoleMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wulian.common.constants.UserConstant;
import com.wulian.common.controller.BaseController;
import com.wulian.common.dto.SysUserDto;
import com.wulian.common.dto.UserInfo;
import com.wulian.common.entity.SysUser;
import com.wulian.common.euums.AppErrorCodeEnum;
import com.wulian.common.util.JSONUtil;
import com.wulian.common.util.MD5;
import com.wulian.common.util.Query;
import com.wulian.common.util.RegUtil;
import com.wulian.common.vo.PatrolRecordError;
import com.wulian.common.vo.PatrolRecordSuccess;
import com.wulian.common.vo.ResultMoudel;
import com.wulian.common.vo.UserVO;
import com.wulian.user.dto.DirectLeadership;
import com.wulian.user.entity.PostUser;
import com.wulian.user.entity.SysTree;
import com.wulian.user.entity.SysUserRole;
import com.wulian.user.mapper.PostUserMapper;
import com.wulian.user.mapper.SysUserRoleMapper;
import com.wulian.user.service.SysTreeService;
import com.wulian.user.service.SysUserService;
import com.wulian.user.service.UserService;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 
* @ClassName: UserController 
* @Description: TODO(用户控制器) 
* @author 马志豪
* @date 2019年9月16日 下午3:02:28 
*
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController<UserInfo> {

    private static final long TOKEN_EXPIRE_TIME = 60 * 60 * 24 * 30 * 12;
    @Autowired
    private SysUserService userService;
    
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    private SysTreeService sysTreeService;

    @Autowired
    private UserService userServiceu;

    @Autowired
    private PostUserMapper postUserMapper;

//    @Autowired
//    private SysRoleMapper sysRoleMapper;

    //查询所有的用户
    @GetMapping("/getUsers")
    public ResultMoudel getUsers(){
        Map<String, Object> map = new HashMap<>();
        map.put("status",0);
        ResultMoudel resultMoudel = new ResultMoudel();
        return new ResultMoudel<List>("success",userService.selectByMap(map));
    }

    //模糊查询用户名和id列表 id;id;id
    @GetMapping("/getUsersByIds")
    public ResultMoudel getUsersByName(String ids){
        Map<String, Object> map = new HashMap<>();
        map.put("ids",ids != null ? StringUtils.split(ids,";") : null);
        return new ResultMoudel<>("success",userService.getUsersByName(map));
    }

    @GetMapping("/getUserInfoForApp")
    public Object getUserInfoByApp(){
        SysUser user = null;
        try {
            user = getCurrentUser().getSysUser();
            user.setPassword("");
        } catch (Exception e) {
            PatrolRecordError patrolRecordError = new PatrolRecordError();
            patrolRecordError.setErr_msg(AppErrorCodeEnum.ERROR_30002_INNER.getDescribe());
            patrolRecordError.setErr_code(AppErrorCodeEnum.ERROR_30002_INNER.getErrorCode());
            return patrolRecordError;
        }
        PatrolRecordSuccess<Object> success = new PatrolRecordSuccess<>();
        success.setBody(user);
        return success;
    }

    @PostMapping("/updateNameForAppByToken")
    public Object updateNameForAppByToken(@RequestBody Map<String,String> map){
        String name =  map.containsKey("name") ? map.get("name"): null;
        String phone =  map.containsKey("phone") ? map.get("phone"): null;
        String email =  map.containsKey("email") ? map.get("email"): null;
        //String name,String phone,String email
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(phone)){
            PatrolRecordError patrolRecordError = new PatrolRecordError();
            patrolRecordError.setErr_code(AppErrorCodeEnum.ERROR_30000_PARAM.getErrorCode());
            patrolRecordError.setErr_msg(AppErrorCodeEnum.ERROR_30000_PARAM.getDescribe());
            return patrolRecordError;
        }
        //查询当前用户
        try {
            UserInfo user = getCurrentUser();
            SysUser userRedis = user.getSysUser();
            SysUser userMysql = userService.selectById(userRedis.getUserId());
            userMysql.setUpdateTime(new Date());
            userMysql.setName(name);
            userMysql.setPhone(phone);
            if (StringUtils.isNotEmpty(email) ){
                userMysql.setEmail(email);
            }
            //修改mysql数据库
            boolean flag = userService.updateById(userMysql);
            if (flag){
                //修改redis
                user.getSysUser().setName(name);
                user.getSysUser().setPhone(phone);
                user.getSysUser().setEmail(email);
                String redisToken = redisTemplate.opsForValue().get(UserConstant.USER_ID_TOKEN_PREFIEX+userRedis.getUserId());
                redisTemplate.opsForValue().set(UserConstant.USER_TOKEN_PREFIEX + redisToken, JSONUtil.toJSON(user), TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
                return new PatrolRecordSuccess<>();
            }else {
                //服务器内部错误
                return PatrolRecordError.getInnerError();
            }
        } catch (Exception e) {
            //服务器内部错误
            return PatrolRecordError.getInnerError();
        }

    }


    @PostMapping("/getUserInfo")
	public ResultMoudel getUserInfo(){
    	UserInfo user = getCurrentUser();
		System.out.println(JSONUtil.toJSON(user));
		return new ResultMoudel(ResultMoudel.SUCCESS_FLAG, user);
	}
    
    /**
     * 获取当前用户信息（角色、权限）
     * 并且异步初始化用户部门信息
     *
     * @param userVo 当前用户信息
     * @return 用户名
     */
    @GetMapping("/info")
    public ResultMoudel<UserInfo> user(UserVO userVo) {
        UserInfo userInfo = userService.findUserInfo(userVo);
        return new ResultMoudel<>(ResultMoudel.SUCCESS_FLAG,userInfo);
    }

    /**
     * 通过ID查询当前用户信息
     *
     * @param id ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public UserVO user(@PathVariable Integer id) {
        return userService.selectUserVoById(id);
    }
    
    @GetMapping("/getUser")
    public UserVO getUser(Integer id) {
        return userService.selectUserVoById(id);
    }

    /**
     * 删除用户信息
     *
     * @param id ID
     * @return R
     */
    @ApiOperation(value = "删除用户", notes = "根据ID删除用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int", paramType = "path")
    @DeleteMapping("/{id}")
    public ResultMoudel userDel(@PathVariable Integer id) {
        SysUser sysUser = userService.selectById(id);
        if(null == sysUser){
            return new ResultMoudel().success("用户信息不存在");
        }
        SysUser updateUser = getCurrentUser().getSysUser();
        Boolean deleteFlag = userService.deleteUserById(sysUser,updateUser);
        if(deleteFlag){
        	return new ResultMoudel(ResultMoudel.SUCCESS_FLAG,"删除成功");
        }
        return new ResultMoudel<>(ResultMoudel.ERROR_FLAG,"删除失败");
    }

    /**
     * 添加用户
     *
     * @param userDto 用户信息
     * @return success/false
     */
    @PostMapping
    public ResultMoudel user(@RequestBody SysUserDto userDto) {
        Integer userId = getCurrentUser().getSysUser().getUserId();
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userDto, sysUser);
        sysUser.setDelFlag("0");
        // 当Status不是2时，填写默认值
        if(sysUser.getStatus() != null){
            if(sysUser.getStatus() != 2)
                sysUser.setStatus( 0 );
        }else{
            sysUser.setStatus( 0 );
        }
        sysUser.setUpdateTime( new Date(  ) );
        sysUser.setCreateTime( new Date(  ) );
        boolean b = RegUtil.checkPassword1(userDto.getNewpassword1());
        if(!b){
            return new ResultMoudel("error", "必须是包含大小写字母、数字、特殊符号的8位以上组合");
        }
        boolean b1 = RegUtil.checkPassword2(userDto.getNewpassword1());
        if(!b1){
            return new ResultMoudel("error", "不能含有3个相同连续字符");
        }
        sysUser.setPassword(MD5.sign(userDto.getNewpassword1(), null, "utf-8"));
        sysUser.setUserType("1");//机构人员
        String companyLogo = getCurrentUser().getSysUser().getCompanyLogo();
        String userName = companyLogo + "-"+sysUser.getUsername();
        sysUser.setUsername(userName);
        sysUser.setCompanyId(getCurrentUser().getSysUser().getCompanyId());
        sysUser.setCreateId(userId);
        sysUser.setUpdateId(userId);
        userService.insert(sysUser);
        // 添加用户与role之间的关系
        userDto.getRole().forEach(roleId -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(sysUser.getUserId());
            userRole.setRoleId(roleId);
            userRole.insert();
        });
        userService.updateRedis();
        return new ResultMoudel<>(ResultMoudel.SUCCESS_FLAG,Boolean.TRUE);
    }

    /**
     * 更新用户信息
     *
     * @param userDto 用户信息
     * @return R
     */
    @PutMapping
    public ResultMoudel userUpdate(@RequestBody SysUserDto userDto) {
        SysUser user = userService.selectById(userDto.getUserId());
        //由于传递的没有密码信息,修改时密码字段不可为空,因此从修改的用户信息中读取密码赋值到userDto
        userDto.setPassword(user.getPassword());
        Boolean updateUserFlag = userService.updateUser(userDto, user.getUsername());
        if(updateUserFlag){
        	return new ResultMoudel(ResultMoudel.SUCCESS_FLAG,"更新用户信息成功");
        }
        return new ResultMoudel("error","更新用户信息失败");
    }

    /**
     * 更新用户状态
     *
     * @param id
     * @return Result
     */
    @PutMapping("/updateStatuss/{id}")
    public ResultMoudel updateStatuss(@PathVariable Integer id) {
        SysUser sysUser = userService.selectById(id);
        if(0==sysUser.getStatus()){
            sysUser.setStatus( 1 );
        }else if(1==sysUser.getStatus()){
            sysUser.setStatus( 0 );
        }
        userService.updateUserStatus(sysUser);
        return new ResultMoudel(ResultMoudel.SUCCESS_FLAG,Boolean.TRUE);
    }

    /**
     * 通过用户名查询用户及其角色信息
     *
     * @param username 用户名
     * @return UseVo 对象
     */
    @GetMapping("/findUserByUsername/{username}")
    public UserVO findUserByUsername(@PathVariable String username) {
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	paramMap.put("username", username);
    	paramMap.put("status", 0);
        return userService.findUserByUsername(paramMap);
    }

    /**
     * 通过手机号查询用户及其角色信息
     *
     * @param mobile 手机号
     * @return UseVo 对象
     */
    @GetMapping("/findUserByMobile/{mobile}")
    public UserVO findUserByMobile(@PathVariable String mobile) {
        return userService.findUserByMobile(mobile);
    }

    /**
     * 通过OpenId查询
     *
     * @param openId openid
     * @return 对象
     */
    @GetMapping("/findUserByOpenId/{openId}")
    public UserVO findUserByOpenId(@PathVariable String openId) {
        return userService.findUserByOpenId(openId);
    }

    /**
     * 分页查询用户(只检索当前用户所属部门及下属部门下的所有用户)
     *
     * @param map 参数集
     * @param pageSize 总页数
     * @param num 当前页码
     * @return 用户集合
     */
    @RequestMapping("/userPage")
    public Page userPage(@RequestBody Map<String,Object> map ,@RequestParam(defaultValue = "10",required = false) int pageSize,@RequestParam(defaultValue = "0",required = false) int num) {
//        UserVO userVO = null;
//        Integer deptId = null == userVO ? null : userVO.getDeptId();
    	UserInfo user = getCurrentUser();
        UserVO userVO = new UserVO();

        String name =  (String) (map.containsKey("name") ? map.get("name"): null);
        Object deptId =  map.containsKey("deptId") ? map.get("deptId"): null;
        String username =  (String) (map.containsKey("username") ? map.get("username"): null);

        Integer ideptId = 0;
        //获取当前用户所属部门ID
        if (deptId != null)
            ideptId = (Integer) deptId;
        else
            ideptId = user.getSysUser().getDeptId();

    	userVO.setDeptId(ideptId);

        return userService.selectWithRolePage(new Query(map),userVO);
    }


    /**
     * 修改个人信息
     *
     * @param userDto userDto
     * @param userVo  登录用户信息
     * @return success/false
     */
    @PutMapping("/editInfo")
    public ResultMoudel editInfo(@RequestBody SysUserDto userDto, UserVO userVo) {
        return userService.updateUserInfo(userDto, userVo.getUsername());
    }

    /**
     * 通过workNumber修改机构
     *
     * @param sysUser
     * @return success/false
     */
    @PutMapping("/updateDeptIdByWorkNumber")
    public Boolean updateDeptIdByWorkNumber(@RequestBody SysUser sysUser) {
        return userService.updateDeptIdByWorkNumber(sysUser);
    }

    /**
     * create by: liupdatePassword
     * description: 修改密码
     * create time: 2020/03/06 15:57
     */
    @PostMapping("/updatePassword")
    public ResultMoudel updatePassword(@RequestBody SysUserDto userDto) {
        UserInfo user = getCurrentUser();
        if (user==null||StringUtils.isBlank(userDto.getOldPassword())||StringUtils.isBlank(userDto.getNewpassword1())){
            return new ResultMoudel("error", "参数不全");
        }
        userDto.setUserId(user.getSysUser().getUserId());
        ResultMoudel resultMoudel= userService.updatePassword(userDto);
        return resultMoudel;
    }
    
    /**
     * 
    * @Title: chooseDept
    * @Description:(选择的部门id获取下级部门集合)
    * @param @param chooseDeptId
    * @param @return    参数
    * @return ResultMoudel    返回类型
    * @author mzh
    * @date 2020年7月9日
    * @version V1.0
    * @throws
     */
    @PostMapping("/chooseDept")
    public ResultMoudel<String> chooseDept(Integer chooseDeptId){
    	if(null != chooseDeptId){
    		UserInfo currentUser = getCurrentUser();
    		Integer deptId = currentUser.getSysUser().getDeptId();
        	//当前用户所在部门及其下属部门集合
            SysTree sysTree = new SysTree();
            sysTree.setTypeId(2);
            sysTree.setChriledId(Long.valueOf(deptId));
            //获取当前用户所属部门下所有的部门信息
            List<SysTree> selectListChannel = sysTreeService.selectListChannel(sysTree);
            //转换为List<String>
            List<String> deptIdList = selectListChannel.stream()
                    .map(st -> String.valueOf(st.getChriledId())).collect(Collectors.toList());
            if(null != deptIdList && deptIdList.size() > 0){
            	boolean flag = deptIdList.contains(String.valueOf(chooseDeptId));
            	//未选择超出当前登录人的部门id范围
            	if(flag){
            		sysTree.setChriledId(Long.valueOf(chooseDeptId));
            		//获取当前用户所属部门下所有的部门信息
            		selectListChannel = sysTreeService.selectListChannel(sysTree);
                    //转换为List<String>
            		deptIdList = selectListChannel.stream()
                            .map(st -> String.valueOf(st.getChriledId())).collect(Collectors.toList());
            		//项目数据
            		/*SysProjectDto sysProject = new SysProjectDto();
            		sysProject.setStatus(2);
                    sysProject.setDelFlag(0);*/
                    String chooseDeptIds = StringUtils.join(deptIdList.toArray(), ",");
                   /* sysProject.setDeptIds(chooseDeptIds);
            		List<SysProject> projectList = projectService.findByName(sysProject);
                    if(null != projectList && projectList.size() > 0){
                    	List<String> chooseItemIdList = projectList.stream()
                                .map(sp -> String.valueOf(sp.getProjectId())).collect(Collectors.toList());
                    	String chooseItemIds = StringUtils.join(chooseItemIdList.toArray(), ",");
                    	log.info("选择的部门id获取下级部门集合中获取chooseItemIds:{}",chooseItemIds);
                    	currentUser.setChooseItemIds(chooseItemIds);
                    }else{
                    	currentUser.setChooseItemIds("0");//0代表没有项目
                    }*/
            		currentUser.setChooseDeptId(chooseDeptId);
            		currentUser.setChooseDeptIds(chooseDeptIds);
            		String userJson = JSONUtil.toJSON(currentUser);
            		String userId = String.valueOf(currentUser.getSysUser().getUserId());
            		String redisToken = redisTemplate.opsForValue().get(UserConstant.USER_ID_TOKEN_PREFIEX + userId +"_pc");
            		if (StringUtils.isNotEmpty(redisToken)) {
            			redisTemplate.opsForValue().set(UserConstant.USER_TOKEN_PREFIEX + redisToken, userJson,
								TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
            		log.info("切换机构后同步当前用户信息至redis结果为userJson:{}",userJson);
            			return new ResultMoudel<String>(ResultMoudel.SUCCESS_FLAG,"选择机构成功");
            		}
            	}
            }
    	}
    	
    	return new ResultMoudel<String>(ResultMoudel.ERROR_FLAG,"选择机构失败");
    }


    /**
     * 功能描述: <br>
     * 〈查询本公司所有员工〉
     * @Param:
     * @Return:
     * @Author: caifulin
     * @Date: 2020/10/27
     */
    @PostMapping("/getCompanyUser")
    public ResultMoudel getCompanyUser(@RequestBody Map<String,Object> map ,@RequestParam(defaultValue = "10",required = false) int pageSize,@RequestParam(defaultValue = "0",required = false) int num ){
        Integer companyId = getCurrentUser().getSysUser().getCompanyId();
        Integer userId = getCurrentUser().getSysUser().getUserId();
        //map.put("userId",userId);
        map.put("companyId",companyId);
        Page<DirectLeadership> page = new Page<>(num,pageSize);
        Page<DirectLeadership> companyUser = userServiceu.getCompanyUser(page, map);
        return new ResultMoudel().success(companyUser);
    }


    @PostMapping("/getCompanyLogo")
    public ResultMoudel getCompanyUser(){
        String companyLogo = getCurrentUser().getSysUser().getCompanyLogo();
        return new ResultMoudel().success(companyLogo);
    }
    /**
     * 功能描述: <br>
     * 〈查询本公司所有员工〉
     * @Param:
     * @Return:
     * @Author: caifulin
     * @Date: 2020/10/27
     */
    @PostMapping("/queryUserByCompanyId")
    public ResultMoudel queryUserByCompanyId(@RequestBody Map<String,Object> param){
        Integer companyId = getCurrentUser().getSysUser().getCompanyId();
        if(null == companyId){
            return new ResultMoudel().error("人员信息异常");
        }

        List<SysUser> sysUsers = userService.queryUserByCompanyId(companyId,param);
        return new ResultMoudel().success(sysUsers);
    }

    /**
     * 功能描述: <br>
     * 〈查询本公司所有员工--绑定过对应岗位的附上默认值〉
     * @Param:
     * @Return:
     * @Author: caifulin
     * @Date: 2020/10/27
     */
    @PostMapping("/getCompanyUserFilterPost")
    public ResultMoudel getCompanyUserFilterPost(@RequestBody Map<String,Object> map ,@RequestParam(defaultValue = "10",required = false) int pageSize,@RequestParam(defaultValue = "0",required = false) int pageNumber ){
        if(null == map.get("id") ){
            return new ResultMoudel().error("参数错误");
        }
        Integer companyId = getCurrentUser().getSysUser().getCompanyId();
        map.put("companyId",companyId);
        Page<DirectLeadership> page = new Page<>(pageNumber,pageSize);
        Page<DirectLeadership> companyUser = userServiceu.getCompanyUser(page, map);
        List<DirectLeadership> records = companyUser.getRecords();
        if(null == records || 0 == records.size()){
            return new ResultMoudel().success(null);
        }
        PostUser postUser = new PostUser();
        postUser.setDelFlag(0);
        postUser.setCompanyId(companyId);
        postUser.setPostId(Integer.valueOf(map.get("id").toString()));
        EntityWrapper<PostUser> postUserEntityWrapper = new EntityWrapper(postUser);
        List<PostUser> postUsers = postUserMapper.selectList(postUserEntityWrapper);
        List<Integer> portUserId = postUsers.stream().map(e -> e.getUserId()).collect(Collectors.toList());
        records.forEach( e->{
            portUserId.forEach( t -> {
                if(e.getUserId() == t.intValue()){
                    e.setChecked(true);
                }
            });
        });
        companyUser.setRecords(records);
        return new ResultMoudel().success(companyUser);
    }
    /**
     * 功能描述: <br>
     * 〈重置密碼〉
     * @Param:
     * @Return:
     * @Author: caifulin
     * @Date: 2020/7/17
     */
    @PostMapping("/initPassword")
    @ApiOperation(value = "重置密碼",httpMethod = "POST")
    public ResultMoudel initPassword(@RequestBody SysUser sysUserDto) {
        SysUser sysUser = userService.selectById(sysUserDto.getUserId());
        if(null == sysUser){
            return new ResultMoudel().error("用户信息错误");
        }
        UserInfo currentUser = getCurrentUser();
        ResultMoudel resultMoudel= userService.initPassword(currentUser,sysUser);
        return resultMoudel;
    }

    /**
     * 功能描述: <br>
     * 更新openid
     * @Param:
     * @Return:
     * @Author: huangjunren
     * @Date: 2021/5/13
     */
    @PostMapping("/updateOpenID")
    @ApiOperation(value = "更新Openid",httpMethod = "POST")
    public ResultMoudel updateOpenID(@RequestBody SysUser sysUserDto) {
        SysUser sysUser = userService.selectById(sysUserDto.getUserId());
        if(null == sysUser){
            return new ResultMoudel().error("用户信息错误");
        }
        ResultMoudel resultMoudel= userService.updateOpenID(sysUserDto);
        return resultMoudel;
    }
    
    @PostMapping("/isSuperAdmin")
   	public ResultMoudel isSuperAdmin(){
       	UserInfo user = getCurrentUser();
       	SysUser sysUser = user.getSysUser();
       	
       	HashMap<String,Object> columnMap = new HashMap<String,Object>();
       	columnMap.put("user_id", sysUser.getUserId());
       	
       	List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectByMap(columnMap);
       	
       	long count = sysUserRoleList.stream().filter(sur -> "1".equals(String.valueOf(sur.getRoleId()))).count();
       	
       	boolean flag = false;
       	if(count > 0){
       		flag = true;
       	}
       	
   		return new ResultMoudel(ResultMoudel.SUCCESS_FLAG, flag);
   	}
    
}
